package com.pth.dao.impl;

import java.sql.SQLException;
import java.util.List;

import org.hibernate.HibernateException;
import org.hibernate.Session;
import org.springframework.orm.hibernate3.HibernateCallback;
import org.springframework.orm.hibernate3.HibernateTemplate;

import com.pth.dao.PolicyDAO;
import com.pth.model.Policy;

public class PolicyDAOImpl implements PolicyDAO {

	private HibernateTemplate hibernateTemplate;

	public void setHibernateTemplate(HibernateTemplate hibernateTemplate) {
		this.hibernateTemplate = hibernateTemplate;
	}

	public HibernateTemplate getHibernateTemplate() {
		return hibernateTemplate;
	}

	public void delete(Policy policy) {

		hibernateTemplate.delete(policy);
	}

	public int getAllNum() {

		return hibernateTemplate.find("from Policy").size();
	
	}

	@SuppressWarnings("unchecked")
	public List<Policy> getPolicies(final int pagesize,final int offset) {

		final String hqlString="from Policy p order by p.publishtime desc";
		
		List<Policy> list=hibernateTemplate.executeFind(new HibernateCallback() {

			public Object doInHibernate(Session arg0) throws HibernateException,
					SQLException {

				return arg0.createQuery(hqlString).setFirstResult(offset).setMaxResults(pagesize).list();
				
			}
		});
		
		return list;
	
	}

	public Policy getPolicyByid(int id) {

		return hibernateTemplate.get(Policy.class, id);
		
	}

	public void save(Policy policy) {

		hibernateTemplate.save(policy);
		
	}

	public void update(Policy policy) {

		hibernateTemplate.update(policy);
		
	}

	@SuppressWarnings("unchecked")
	public List<Policy> getPoliciesOrderByscannum(final int offset,final int pagesize) {

		final String hqlString="from Policy p order by p.scanNum desc";
		
		List<Policy> list=hibernateTemplate.executeFind(new HibernateCallback() {

			public Object doInHibernate(Session arg0) throws HibernateException,
					SQLException {

				return arg0.createQuery(hqlString).setFirstResult(offset).setMaxResults(pagesize).list();
				
			}
		});
		
		return list;
		
		
		
		
	}

	public List<Policy> getPolicies() {
		return hibernateTemplate.find("from Policy");
	}
	
	
	
}
